<template>
  <div id="app">
    <header class="header">
      <div class="logo"></div>
    </header>
    <div class="modal">
      <div class="infor-login">
        <div class="top">
          新用户注册
        </div>
        <input
          placeholder="手机号"
          class="phone"
          v-model="phone"
          :class="borderShow ? '' : 'borderRed'"
        />
        <div class="code">
          <input placeholder="验证码" class=" phone-code" v-model="code" />
          <button class="btn" @click="getCode">{{ text }}</button>
        </div>
        <div class="text">
          <span class="account">已有账号，</span>
          <span class="login-text" @click="login()">立即登录</span>
        </div>
        <div class="login-btn" @click="register" @keyup.enter="register">注册</div>
      </div>
    </div>
    <footer>
      Copyright © 2020 Nanjing Yanmemoir Cultural Media Company. All rights
      reserved.
    </footer>
  </div>
</template>

<script>
export default {
  name: "register",
  props: {},
  data() {
    return {
      value: false,
      show: true,
      phone: "",
      code: "",
      borderShow: true,
      text: "获取验证码",
      number: 60,
      disable: false,
    };
  },
  mounted() {
    this.getRem(1920, 100);
  },
  watch: {
    //监听手机号
    phone: {
      handler(newName, oldName) {
        console.log(newName);
        let reg = /^[1][3,4,5,7,8][0-9]{9}$/;
        console.log(reg.test(newName));
        if (reg.test(newName)) {
          this.borderShow = true;
        } else {
          this.borderShow = false;
        }
      },
      // immediate: true,
    },
  },
  methods: {
    //获取验证码
    async getCode() {
      console.log(this.code);
      this.timer(60);
      if (this.borderShow && this.disable == false) {
        const result = await this.$post(`/laiwen/message/frontend/test?phoneNumber=${this.phone}`,{})
        this.disable = true;
      }
    },
    //注册
    async register() {
      const result = await this.$fetch( `/laiwen/user/frontend/save?code=${this.code}&phone_number=${this.phone}`,{})
      
      if (result.msg == "注册成功") {
          localStorage.setItem("user", JSON.stringify(result.user));
          //存储token
          localStorage.setItem("token", result.token);
          this.$router.push({
            path: "/index",
          });
        } else {
          this.$message.error("输入的验证码有误或账号已经注册");
        }
    },
    //60秒倒计时
    timer(num) {
      let time = setInterval(() => {
        if (num > 0) {
          num--;
          this.text = `${num}秒`;
        } else {
          this.text = `重新发送`;
          clearInterval(time);
          this.disable = false;
        }
      }, 1000);
    },
    //跳到登入
    login() {
      this.$router.push({
        path: "/",
      });
    },
  },
};
</script>
<style scoped src="../assets/css/register.css"></style>
